package com.jason.ladder.dao.hibernate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.jason.ladder.dao.GameDao;
import com.jason.ladder.entityManager.EMF;
import com.jason.ladder.model.Game;
import com.jason.ladder.model.User;
@Repository("gameDao")
public class GameDaoHibernate implements GameDao {

	public GameDaoHibernate() {
		
		
	}

	@Override
	public Game saveGame(Game game) {
	    	EntityManager em = EMF.get().createEntityManager();
	    	try{
	    		em.getTransaction().begin();
	    		em.persist(game);
	    	//	em.flush();
	    	}finally{
	    		em.getTransaction().commit();
	    		em.close();
	    	}
	        return game;
	   
	}

	@Override
	public List<Game> getGamesForTimeFrame(User user, Date startDate,
			Date endDate) {
		EntityManager em = EMF.get().createEntityManager();
		List<Game> games = new ArrayList<Game>();
		try{
			Query query = em.createQuery("select g from Game g where you = :userId and (playDate between :startDate and :endDate) order by playDate asc");
			query.setParameter("userId", user.getId());
			query.setParameter("startDate", startDate);
			query.setParameter("endDate", endDate);
			games = query.getResultList();
		}finally{
			em.close();
		}
		
		return games;
	}

}
